package com.java1234.common.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 邓文
 */
@Component
public class CspFilter extends OncePerRequestFilter {

    private static final Logger logger = LoggerFactory.getLogger(CspFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException{
        try {
            // 添加CSP头
//            String cspHeader = "default-src 'self'; script-src 'self' https://sf-works.oss-cn-hangzhou.aliyuncs.com; object-src 'none'; style-src 'self' 'unsafe-inline'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; sandbox allow-scripts allow-same-origin";
            String cspHeader = "default-src 'self'; script-src 'self' https://bucket-ilms.oss-cn-hangzhou.aliyuncs.com; object-src 'none'; style-src 'self' 'unsafe-inline'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; sandbox allow-scripts allow-same-origin";
            response.addHeader("Content-Security-Policy", cspHeader);
            logger.info("CSP header set: {}", cspHeader);
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            logger.error("Error setting CSP header", e);
            throw new ServletException("CSPFilter error", e);
        }
    }
}